<template>
  <view class="page-container w-[750rpx] mx-auto bg-[#f0f2f5] min-h-screen">
    <!-- 头部导航 -->
    <!-- Header -->
    <PageHeader title="" :showBack="true" :onlyBack="true" />
    <view
      class="header bg-gradient-to-r from-[#4361ee] to-[#3f37c9] text-white p-[30rpx] shadow-md sticky top-0 z-[2]"
    >
      <view class="header-content flex justify-center items-center w-full">
        <!-- <view
          class="back-btn w-[80rpx] h-[80rpx] flex items-center justify-center mr-[30rpx]"
          @click="handleBack"
        >
          <IconFont
            font-class-name="iconfont"
            class-prefix="icon"
            name="arrow-left"
            size="36"
          />
        </view> -->
        <view class="header-title text-[36rpx] text-center font-bold flex-1">任务详情</view>
        <!-- <view
          class="action-icon w-[80rpx] h-[80rpx] flex items-center justify-center mr-[15rpx]"
          @click="handleShare"
        >
          <IconFont
            font-class-name="iconfont"
            class-prefix="icon"
            name="share-alt"
            size="32"
          />
        </view>
        <view
          class="action-icon w-[80rpx] h-[80rpx] flex items-center justify-center"
          @click="handleMore"
        >
          <IconFont
            font-class-name="iconfont"
            class-prefix="icon"
            name="ellipsis-vertical"
            size="32"
          />
        </view> -->
      </view>
    </view>

    <view class="container px-[30rpx]">
      <!-- 任务详情卡片 -->
      <view
        class="task-card bg-white rounded-[30rpx] p-[50rpx] my-[40rpx] shadow-sm"
      >
        <view class="task-header flex flex-col mb-[40rpx]">
          <!-- 标题 -->
          <text
            class="task-title text-[40rpx] font-bold text-[#212529] mb-[20rpx]"
          >
            {{ title }}
          </text>

          <!-- 价格区域（去除左侧内边距，确保左对齐） -->
          <view
            class="task-price self-start text-[#f72585] pl-0 pr-[40rpx] py-[16rpx] rounded-[60rpx] font-bold text-[36rpx] min-w-[240rpx] border border-[#f72585]"
          >
            <text class="inline-block">¥{{ totalAmount }}</text>
          </view>
        </view>

        <!-- 任务元信息（使用v-for渲染） -->
        <view
          class="task-meta flex flex-wrap gap-[30rpx] mb-[50rpx] pb-[40rpx] border-b border-[#e9ecef]"
        >
          <view
            class="meta-item flex items-center text-[28rpx]"
            v-for="(meta, index) in taskMeta"
            :key="index"
          >
            <IconFont
              font-class-name="iconfont"
              class-prefix="icon"
              :name="meta.icon"
              class="mr-[16rpx] text-[#4361ee]"
              size="18"
            />
            <text>{{ meta.text }}</text>
          </view>
        </view>

        <!-- 任务描述 -->
        <view class="mb-[60rpx]">
          <view
            class="section-title flex items-center text-[36rpx] font-bold mb-[30rpx]"
          >
            <IconFont
              font-class-name="iconfont"
              class-prefix="icon"
              name="renwu"
              class="mr-[20rpx] text-[#4361ee]"
              size="36"
            />
            <text>任务描述</text>
          </view>
          <view class="task-description text-[28rpx] leading-[48rpx]">
            <view>{{ text }}</view>
          </view>
        </view>

        <!-- 任务阶段（使用v-for渲染） -->
        <view class="mb-[60rpx]">
          <view
            class="section-title flex items-center text-[36rpx] font-bold mb-[30rpx]"
          >
            <IconFont
              font-class-name="iconfont"
              class-prefix="icon"
              name="list-fourliebiao"
              class="mr-[20rpx] text-[#4361ee]"
              size="26"
            />
            <text>任务阶段</text>
          </view>
          <view class="stages-container">
            <view
              class="stage-card bg-[#f8f9fa] rounded-[24rpx] p-[40rpx] mb-[30rpx] border-l-[8rpx] border-[#4361ee]"
              v-for="(stage, index) in stages"
              :key="index"
            >
              <view class="stage-header flex justify-between mb-[30rpx]">
                <text class="stage-name text-[32rpx] font-semibold">{{
                  stage.task_description
                }}</text>
                <text class="stage-price text-[#f72585] font-bold text-[32rpx]"
                  >¥{{ stage.price }}</text
                >
              </view>
              <view class="stage-details pl-[20rpx]">
                <view
                  class="flex items-start mb-[16rpx]"
                  v-for="(detail, i) in stage.details"
                  :key="i"
                >
                  <text
                    class="text-[#4361ee] text-[36rpx] leading-[40rpx] mr-[16rpx]"
                    >•</text
                  >
                  <text class="text-[28rpx] leading-[40rpx]">{{ detail }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 执行者要求（使用v-for渲染） -->
        <view class="mb-[60rpx]">
          <view
            class="section-title flex items-center text-[36rpx] font-bold mb-[30rpx]"
          >
            <IconFont
              font-class-name="iconfont"
              class-prefix="icon"
              name="yirenzhengyonghu"
              class="mr-[20rpx] text-[#4361ee]"
              size="26"
            />
            <text>执行者要求</text>
          </view>
          <view class="requirement-list bg-[#f8f9fa] rounded-[24rpx] p-[40rpx]">
            <view
              class="requirement-item flex items-center mb-[30rpx]"
              v-for="(req, index) in requirements"
              :key="index"
            >
              <view
                class="requirement-icon w-[10rpx] h-[10rpx] flex items-center justify-center bg-[#4361ee] text-white rounded-full mr-[5rpx]"
              >
                <IconFont name="check" size="1" />
              </view>
              <text class="requirement-text text-[28rpx] flex-1">{{
                req.text
              }}</text>
              <view
                class="requirement-status px-[24rpx] py-[6rpx] rounded-[40rpx] text-[24rpx]"
                :class="
                  req.status === 'met'
                    ? 'bg-[#d4edda] text-[#155724]'
                    : 'bg-[#f8d7da] text-[#721c24]'
                "
              >
                {{ req.status === "met" ? "已满足" : "未满足" }}
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 发布者信息 -->
      <view class="mb-[40rpx]">
        <view
          class="section-title flex items-center text-[36rpx] font-bold mb-[30rpx]"
        >
          <IconFont
            font-class-name="iconfont"
            class-prefix="icon"
            name="service-provider_fill"
            class="mr-[20rpx] text-[#4361ee]"
            size="26"
          />
          <text>任务发布方</text>
        </view>
        <view
          class="publisher-card bg-white rounded-[30rpx] p-[40rpx] shadow-sm border border-[#e9ecef]"
        >
          <view class="publisher-header flex flex-col items-center mb-[40rpx]">
            <!-- 头像部分 - 顶部 -->
            <view
              class="publisher-avatar w-[120rpx] h-[120rpx] rounded-full bg-[#e9ecef] flex items-center justify-center mb-[20rpx]"
            >
              <text class="text-[48rpx] font-bold text-[#4361ee]">科</text>
            </view>

            <!-- 公司名称 - 中间 -->
            <text
              class="publisher-name text-[36rpx] font-bold mb-[15rpx] text-center"
              >{{ memberName }}</text
            >

            <!-- 评分和认证信息 - 底部 -->
            <view class="publisher-meta flex flex-row items-center gap-[10rpx]">
              <!-- 星级评分 -->
              <view class="publisher-rating flex items-center">
                <IconFont
                  name="star"
                  class="text-[#ffc107] mr-[6rpx]"
                  size="24"
                />
                <IconFont
                  name="star"
                  class="text-[#ffc107] mr-[6rpx]"
                  size="24"
                />
                <IconFont
                  name="star"
                  class="text-[#ffc107] mr-[6rpx]"
                  size="24"
                />
                <IconFont
                  name="star"
                  class="text-[#ffc107] mr-[6rpx]"
                  size="24"
                />
                <IconFont
                  name="star-half-alt"
                  class="text-[#ffc107] mr-[6rpx]"
                  size="24"
                />
                <text class="text-[24rpx]">(4.7)</text>
              </view>

              <!-- 企业认证 -->
              <view class="flex items-center">
                <IconFont name="badge-check" class="mr-[6rpx]" size="24" />
                <text class="text-[24rpx]">企业认证</text>
              </view>
            </view>
          </view>

          <!-- 发布者统计（使用v-for渲染） -->
          <view
            class="publisher-stats flex justify-around py-[30rpx] border-t border-b border-[#e9ecef] my-[30rpx]"
          >
            <view
              class="stat-item flex-1 text-center"
              v-for="(stat, index) in publisherStats"
              :key="index"
            >
              <text
                class="stat-value block text-[36rpx] font-bold text-[#4361ee]"
                >{{ stat.value }}</text
              >
              <text class="stat-label block text-[24rpx] text-[#6c757d]">{{
                stat.label
              }}</text>
            </view>
          </view>

          <view class="contact-actions flex justify-center">
            <nut-button
              :type="''"
              class="w-full py-[24rpx] bg-[#fa2c19] text-white font-medium flex items-center justify-center rounded-[12rpx] border-0 outline-none"
              @click="contactPublisher"
            >
              <IconFont
                font-class-name="iconfont"
                class-prefix="icon"
                name="xiaoxi"
                class="mr-[16rpx] align-middle"
                size="20"
              />
              联系发布方
            </nut-button>
          </view>
        </view>

        <!-- 平台提示 -->
        <view
          class="task-card bg-[#e6f7ff] border-l-[8rpx] border-[#1890ff] rounded-[24rpx] p-[40rpx] mt-[40rpx] mb-[120rpx]"
        >
          <view class="flex items-center mb-[30rpx]">
            <IconFont
              font-class-name="iconfont"
              class-prefix="icon"
              name="xinxiinfo21"
              class="text-[#1890ff] mr-[16rpx]"
              size="20"
            />
            <text class="text-[32rpx] font-bold">平台提示</text>
          </view>
          <view class="text-[28rpx] leading-[48rpx]">
            <text class="block">1. 任务资金已全额托管在平台，安全有保障</text>
            <text class="block mt-[16rpx]"
              >2. 任务完成后，资金将按阶段划拨到您的账户</text
            >
            <text class="block mt-[16rpx]"
              >3. 平台服务费：普通会员15%，SVIP会员8%</text
            >
            <text class="block mt-[16rpx]"
              >4. 如有纠纷可申请平台仲裁，保障双方权益</text
            >
          </view>
        </view>
      </view>

      <!-- 底部操作栏 -->
      <view
        class="action-bar fixed bottom-0 left-0 w-full bg-white p-[30rpx] shadow-[0_-2px_10px_rgba(0,0,0,0.1)] flex box-border justify-between items-center"
      >
        <view class="action-info flex-1 pr-[30rpx]">
          <view>
            任务总金额：<text
              class="total-price text-[36rpx] font-bold text-[#f72585]"
              >¥{{ totalAmount }}</text
            >
          </view>
          <text class="hint block text-[24rpx] text-[#6c757d]"
            >任务资金已由发布方托管在平台</text
          >
        </view>
        <nut-button :type="'primary'" @click="claimTask" :loading="isLoading">
          <template v-if="isLoading">
            <IconFont
              name="spinner"
              class="mr-[16rpx] animate-spin"
              size="28"
            />
            处理中...
          </template>
          <template v-else-if="isClaimed">
            <IconFont name="check-circle" class="mr-[16rpx]" size="28" />
            已领取
          </template>
          <template v-else> 领取任务 </template>
        </nut-button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from "vue";
import Taro from "@tarojs/taro";
import { IconFont } from "@nutui/icons-vue-taro";
// import { NutButton } from '@nutui/nutui-taro'
import { post } from "@/utils/request";
import { View } from "@tarojs/components";
import PageHeader from "@/components/PageHeader.vue";

interface CategoryColumn {
  cycle: number; // 周期（数字类型）
  describe_str: string; // 描述字符串
  id: number; // 唯一标识ID
  labels: string; // 标签信息
  memberName: string; // 成员名称
  memberStatus: number; // 成员状态（数字类型表示）
  name: string; // 名称(类别)
  title: string; // 标题
  total_amount: number; // 总金额
  status: null | number; // 状态（可能为null或数字类型）
  taskStages: taskStages[]; // 任务阶段列表，包含多个taskStages类型的元素
}

interface CategoryItem {
  columns: CategoryColumn;
  columnNames: string[];
  columnValues: (null | number | string)[];
}

interface taskStages {
  create_time: number;
  cycle: number;
  id: number;
  price: number;
  status: number;
  task_description: string | null;
  task_id: number;
  update_time: number | null;
}

// 任务渲染
const text = ref();
const title = ref();
const totalAmount = ref();
const memberName = ref();

// 获取路由参数
const taskId = Taro.getCurrentInstance().router?.params.id;

// 渲染数据
// const taskData = ref<CategoryColumn>()

// 状态管理
const isLoading = ref(false);
const isClaimed = ref(false);

// 任务元信息数据
const taskMeta = ref([
  { icon: "shijian", text: "截止：2025-07-20" },
  // { icon: 'weizhi', text: '远程任务' },
  { icon: "leibie", text: "设计类" },
  { icon: "yirenzhengyonghu", text: "需实名认证" },
]);

// 任务阶段数据
const stages = ref<taskStages[]>([]);
// 时间戳转换
function formatTimestamp(timestamp: number) {
  const date = new Date(timestamp);
  // 提取各时间部分（注意月份从0开始，需+1）
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0"); // 补0成两位数
  const day = String(date.getDate()).padStart(2, "0");
  // const hours = String(date.getHours()).padStart(2, '0');
  // const minutes = String(date.getMinutes()).padStart(2, '0');
  // const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day}`;
}

// 计算总金额
// const totalAmount = computed(() => {
//   return stages.value
//     .reduce((total, stage) => {
//       return total + (parseFloat(stage.price) || 0);
//     }, 0)
//     .toFixed(2);
// });

// 执行者要求数据
const requirements = ref([
  { text: "必须通过平台实名认证", status: "met" },
  { text: "需提供3个以上UI设计案例", status: "met" },
  { text: "需具备企业官网设计经验", status: "met" },
]);

// 发布者统计数据
const publisherStats = ref([
  { value: "87%", label: "好评率" },
  { value: "42", label: "已发布任务" },
  { value: "98%", label: "完成率" },
]);

// // 任务元信息
// const taskMeta = ref([
//   { icon: 'clock', text: '截止：2025-07-20' },
//   { icon: 'map-marker-alt', text: '远程任务' },
//   { icon: 'layer-group', text: '设计类' },
//   { icon: 'user-check', text: '需实名认证' }
// ])

// 事件处理函数
const handleBack = () => {
  Taro.navigateBack();
};

const handleShare = () => {
  Taro.showToast({
    title: "分享任务功能：生成分享链接或二维码",
    icon: "none",
    duration: 2000,
  });
};

const handleMore = () => {
  Taro.showToast({
    title: "更多选项：举报任务、收藏任务、查看规则",
    icon: "none",
    duration: 2000,
  });
};

const contactPublisher = () => {
  Taro.showToast({
    title: "正在打开聊天窗口...",
    icon: "none",
    duration: 1500,
  });
};

const claimTask = async () => {
  // if (isClaimed.value) return;

  // // 检查未满足的要求
  // const unmetRequirements = requirements.value.filter(
  //   (req) => req.status === "not-met"
  // );
  // if (unmetRequirements.length > 0) {
  //   Taro.showToast({
  //     title: "您尚未满足所有任务要求，请完善资料后再申请",
  //     icon: "none",
  //     duration: 2000,
  //   });
  //   return;
  // }

  // 确认领取
  try {
    const confirmResult = await Taro.showModal({
      title: "确认领取任务",
      content: `任务资金 ¥${totalAmount} 将被冻结，开始执行后按阶段结算`,
      confirmText: "确认领取",
      cancelText: "取消",
    });

    if (confirmResult.confirm) {
      isLoading.value = true;

      // 模拟API请求延迟
      // await new Promise((resolve) => setTimeout(resolve, 1500));
      const res = await post("/task/register", {
        taskId: taskId,
        type: 1,
      });
      console.log('任务领取===>',res)
      if (res.code == 0) {
        isLoading.value = false;
        isClaimed.value = true;

        Taro.showToast({
          title: "任务领取成功！",
          icon: "success",
          duration: 2000,
        });
      }
    }
  } catch (err) {
    isLoading.value = false;
    Taro.showToast({
      title: "操作失败，请重试",
      icon: "none",
      duration: 2000,
    });
  }
};


// 任务详情
const getTaskDetail = async () => {
  const res = await post("/task/detail", { id:taskId });
  console.log("任务详情==>", res);
  if (res.code == 0) {
    title.value = res.data.columns.title;
    text.value = res.data.columns.describe_str;
    totalAmount.value = res.data.columns.total_amount;
    memberName.value = res.data.columns.memberName;
    stages.value = res.data.columns.taskStages.map(
      (item: taskStages) => item.columns
    );
    taskMeta.value[0].text = `截止：${formatTimestamp(
      stages.value[0].create_time
    )}`;
    taskMeta.value[1].text = `${res.data.columns.name}类`;
  }
};
getTaskDetail();

// 任务类型
</script>
